//
//  ZZDeviceManager.m
//  ZZBlue
//
//  Created by stonesMonkey on 2017/9/19.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZZDeviceManager.h"
#import "DeviceTool.h"
#import "ZZDeviceGroup.h"
#import "ZZDeviceList.h"
#import "ZZDeviceCell.h"
#import "ZZDeviceModel.h"
#import "ZDeviceGroupCell.h"
#import "ZZHudView.h"

#define kDeviceCellIdentifier @"deviceCellIdentifier"

@interface ZZDeviceManager()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)ZZDeviceGroup *deviceGroup;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIButton *reloadDeviceBtn;




@end

@implementation ZZDeviceManager

- (void)awakeFromNib {
    
    [super awakeFromNib];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.reloadDeviceBtn.layer.borderWidth = 1;
    self.reloadDeviceBtn.layer.borderColor = [UIColor zColorWithHex:0x747575].CGColor;
    self.reloadDeviceBtn.layer.cornerRadius = 6;
    self.reloadDeviceBtn.layer.masksToBounds = YES;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZZDeviceCell" bundle:nil] forCellReuseIdentifier:kDeviceCellIdentifier];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findDevice) name:kFindNewDeviceConnect object:nil];
    
}

#pragma mark - NOTification
- (void)findDevice {

    [self.tableView reloadData];
}

#pragma mark - tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.deviceGroup.listDevice.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    ZZDeviceList *deviceList = self.deviceGroup.listDevice[section];
    
    return deviceList.deviceList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
     ZZDeviceList *deviceList = self.deviceGroup.listDevice[indexPath.section];
      ZZDeviceModel *model = deviceList.deviceList[indexPath.row];
    
    ZZDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:kDeviceCellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.deviceModel = model;
    cell.colseClickBlock = ^(BOOL isColse, ZZDeviceModel *model) {

        // 关闭按钮点击的方法，这里只需要判断你是否连接这个uuid，如果连接则断开连接即可.

    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 46;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZDeviceList *deviceList = self.deviceGroup.listDevice[indexPath.section];
    ZZDeviceModel *model = deviceList.deviceList[indexPath.row];
    if(model.isConnect) {
        
        return 66;
    }
    
    return 55;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    ZDeviceGroupCell *cell = [ZDeviceGroupCell xibInstance];
    ZZDeviceList *deviceList = self.deviceGroup.listDevice[section];
    cell.deviceList = deviceList;
    
    
    return cell;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return   UITableViewCellEditingStyleDelete;
}
//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ZZDeviceList *list = [[DeviceTool new] deviceGroup].listDevice[indexPath.section];
    ZZDeviceModel *deviceModel =list.deviceList[indexPath.row];
    if (deviceModel.isConnect) {
        
        [MBProgressHUD zAlertError:@"不能删除"];
    }else {
        
        [list.deviceList removeObjectAtIndex:indexPath.row];
        [[DeviceTool new] save];
        [self.tableView reloadData];
    }
    

//    if (editingStyle == UITableViewCellEditingStyleDelete) {
    
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定删除该消息？" preferredStyle:UIAlertControllerStyleAlert];
//        //        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
//        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            //
            //            [_classArray removeObjectAtIndex:indexPath.row];
            //            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            
    
            
//        }]];
//
//        [self.inputViewController presentViewController:alertController animated:YES completion:nil];
//    }
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZHudView *hudView = [ZZHudView xibInstance];
//    hudView.listGroup = [DeviceTool new].deviceGroup.listDevice;
    
    hudView.frame = Z_SCREEN;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
   
//    hudView.musicModel = model;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popView:)];
    hudView.gestureRecognizers = @[tap];
    hudView.userInteractionEnabled = YES;
    ZZDeviceList *list = [[DeviceTool new] deviceGroup].listDevice[indexPath.section];
    ZZDeviceModel *deviceModel =list.deviceList[indexPath.row];
    hudView.deviceModel = deviceModel;
    hudView.deviceGroup = [[DeviceTool new] deviceGroup];
    hudView.deviceList = list;
    hudView.moveCommit = ^ {
        
        
        [self.tableView reloadData];
    };
    
     [window addSubview:hudView];
}

- (void)popView:(UITapGestureRecognizer *)tap {
    
    [tap.view removeFromSuperview];
}

// 连接上之后去判断是否存在这个uuid
- (void)isExitUUID:(NSString *)uuid deviceName:(NSString *)deviceName {


    BOOL isExit = NO;
    for (ZZDeviceList *list in [DeviceTool new].deviceGroup.listDevice) {

        for (ZZDeviceModel *model in list.deviceList) {

            if ([uuid isEqualToString:model.uuid]) {

                // 存在
                isExit = YES;
#pragma 存在UUID
                model.isConnect = YES;

            } else {

                model.isConnect = NO;
            }

        }
    }

    // 如果不存在则需要建立模型，重新添加
    if(!isExit) {

        ZZDeviceModel *model = [ZZDeviceModel new];
        model.deviceName = deviceName;
        model.uuid = uuid;
        model.isConnect = YES;

        [[[DeviceTool new].deviceGroup.listDevice lastObject].deviceList addObject:model];
        [[DeviceTool new] save];
        [self.tableView reloadData];
    }
}

#pragma mark - action
- (IBAction)btnDidClick:(UIButton *)sender {
    
    [self removeFromSuperview];
}

- (IBAction)addSection:(UIButton *)sender {

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"新建分组"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    
    __weak __block UITextField * weakTextFiled = nil;
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = @"请输入组名称";
        weakTextFiled = textField;
    }];
    
    //    alert.view.backgroundColor = [UIColor blackColor];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive
                                                         handler:^(UIAlertAction * action) {}];
    
    UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        
        
        NSString *seactionStr =  weakTextFiled.text;
        if (seactionStr.length == 0) {
            
            [MBProgressHUD zAlertError:@"名字不能为空"];
            
            return ;
        }
        [[DeviceTool new] addSeaction:seactionStr];
        // 刷新
        [self.tableView reloadData];
        
    }];
    
    
    [alert addAction:cancleAction];
    [alert addAction:sureAction];
    
    [self.vc presentViewController:alert animated:YES completion:nil];
}

- (IBAction)reloadBtnDidClick:(UIButton *)sender {
    
    ZZDeviceModel *model = [ZZDeviceModel new];
    model.deviceName = @"热情如火";
    model.uuid = @"887887666";
    model.isConnect = NO;
    
    [[[DeviceTool new].deviceGroup.listDevice lastObject].deviceList addObject:model];
    [[DeviceTool new] save];
    [self.tableView reloadData];
}




#pragma mark - set & get
- (ZZDeviceGroup *)deviceGroup {
    
    if (!_deviceGroup) {
        
        _deviceGroup = [[DeviceTool new] deviceGroup];
    }
    return _deviceGroup;
}

- (IBAction)ABtn:(id)sender {
}

- (IBAction)BBtn:(id)sender {
}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
